package com.bioscript.standalone.dataStructures;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class Project {
	
	private Map<String,Object> map = new HashMap<String, Object>();
	public enum Props
	{
		name,
		size,
		gens;
	}
	
	public Project(String name)
	{
		super();
		map.put(Props.name.toString(), name);
	}
	
	public String getName()
	{
		return (String)map.get(Props.name.toString());
	}
	
	public static List<Project> getProjects(NodeList ndList)
	{
		List<Project> result = new ArrayList<Project>();
		int length = ndList.getLength();
		for (int i = 0; i < length ; i++)
		{
			Element el = (Element) ndList.item(i);
			Project prj = Project.newInstance(el);
			result.add(prj);
		}
		return result;
	}
	
	@SuppressWarnings("unchecked")
	public List<Generation> getGenerations()
	{
		return (List<Generation>)map.get(Props.gens.toString());
	}
	
	public void setSize(int size)
	{
		map.put(Props.size.toString(), String.valueOf(size));
	}
	
	public static Project newInstance(Element el)
	{
		Project project = new Project(el.getAttribute(Props.name.toString()));
		project.setSize(Integer.parseInt(el.getAttribute(Props.size.toString())));
		NodeList gens = el.getElementsByTagName("gen");
		if (gens != null && gens.getLength() > 0)
		{
			project.addGenerations(Generation.getGenerations(gens));
		}
		return project;
	}
	
	@SuppressWarnings("unchecked")
	public void addGeneration(Generation gen)
	{
		List<Generation> gens = null;
		if (map.containsKey(Props.gens.toString()))
		 gens = (List<Generation>)map.get(Props.gens.toString());
		else
			gens = new ArrayList<Generation>();
		gens.add(gen);
		map.put(Props.gens.toString(),gens);
	}
	
	@SuppressWarnings("unchecked")
	public void addGenerations(List<Generation> lst)
	{
		List<Generation> gens = null;
		if (map.containsKey(Props.gens.toString()))
		 gens = (List<Generation>)map.get(Props.gens.toString());
		else
			gens = new ArrayList<Generation>();
		gens.addAll(lst);
		map.put(Props.gens.toString(),gens);
	}
	
	public boolean toXML(Document doc)
	{
		Element el = doc.createElement("prj");
		@SuppressWarnings("unchecked")
		List<Generation> gens = (List<Generation>)map.get(Props.gens.toString());
		if (gens != null)
		{
			for (Generation gen : gens)
			{
				if (!gen.toXML(doc, el)) return false;
			}
		}
		el.setAttribute(Props.name.toString(), getName());
		el.setAttribute(Props.size.toString(), (String)map.get(Props.size.toString()));
		doc.appendChild(el);
		return true;
	}
}
